package com.example.cloud.action;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 可通过@Value注解和Environment对象来获取配置属性
 *
 * @author tongyufu
 */
@RefreshScope
@RestController
public class ConfigAction {

    @Autowired
    private Environment env;
    @Autowired
    private ApplicationContext applicationContext;
    Map<String, Thread> requestThreadMap = new ConcurrentHashMap<>(128);

    /**
     * from
     *
     * @return from
     */
    @RequestMapping("/from")
    public String from() {
        System.out.println("---------" + env.getProperty("from", "没找到from"));
        System.out.println("---------" + env.getProperty("name", "没找到name"));
        return env.getProperty("name", "没找到name");
    }

    @RequestMapping("/wait")
    public String userEvent(@RequestParam String key) {
        try {
            Thread currentThread = Thread.currentThread();
            requestThreadMap.put(key, currentThread);
            System.out.println("===等待:" + key);
            synchronized (currentThread) {
                currentThread.wait(1000 * 60 * 10);
            }
            requestThreadMap.remove(key);
            System.out.println("===被唤醒:" + key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    @RequestMapping("/notify")
    public String notifyUser(@RequestParam String key) {
        Thread currentThread = requestThreadMap.get(key);
        requestThreadMap.remove(key);
        synchronized (currentThread) {
            System.out.println("===唤醒:" + key);
            currentThread.notify();
        }
        return "notify success";
    }

}
